package rabbitmq.pushorpull;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1、建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST); // 设置IP
        connectionFactory.setPort(Constants.PORT); // 设置开放的端口号，需要提前开放
        connectionFactory.setUsername(Constants.USER_NAME); // 设置RabbitMQ 的账号
        connectionFactory.setPassword(Constants.PASSWORD); // 设置RabbitMQ 的密码
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); // 设置 虚拟主机
        Connection connection = connectionFactory.newConnection();
        // 2、开启信道，也就是根据 连接创建信道
        Channel channel = connection.createChannel();
        // 3、声明交换机、使用默认交换机
        // 4、声明队列
        channel.queueDeclare(Constants.MESSAGE_QUEUE,true,false,false,null);

        // 5、 发送消息
        for (int i = 0; i < 10; i++) {
            String msg = "hello message queue...."+i;
            channel.basicPublish("",Constants.MESSAGE_QUEUE, null, msg.getBytes());
        }
        System.out.println("消息发送成功~");
        // 7、释放资源
        channel.close();
        connection.close();
    }
}
